<template>
  <AppModal v-model:visible="modalVisible" :title="modalTitle" width="1000px">
    <div class="flaw-type-detail">
      <div class="detail-header">
        <div class="time-range">
          时间范围：{{ formatDateTime(startTime) }} - {{ formatDateTime(endTime) }}
        </div>
        <div class="flaw-type">
          缺陷类型：<el-tag type="primary">{{ flawType }}</el-tag>
        </div>
      </div>

      <el-table 
        v-loading="loading" 
        :data="flawList" 
        stripe 
        style="width: 100%"
        height="400"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="flawDistance" label="位置(米)" width="100" />
        <el-table-column prop="flawDesc" label="缺陷描述" show-overflow-tooltip />
        <el-table-column prop="level" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityTagType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(getFlawStatus(row))">
              {{ getFlawStatus(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发现时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewImage(row)">
              查看图片
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        class="pagination"
        @size-change="getFlawList"
        @current-change="getFlawList"
      />
    </div>

    <!-- 图片查看器 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :url-list="currentImages"
      @close="imageViewerVisible = false"
    />
  </AppModal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElTable, ElTableColumn, ElTag, ElPagination, ElButton, ElImageViewer } from 'element-plus';
import { formatDateTime } from '@/utils';
import { getFlawsByTime } from '@/api/flaws';
import AppModal from '@/components/common/AppModal.vue';

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  flawType: {
    type: String,
    default: ''
  },
  startTime: {
    type: String,
    default: ''
  },
  endTime: {
    type: String,
    default: ''
  }
});

// Emits
const emit = defineEmits(['update:visible']);

// 响应式数据
const loading = ref(false);
const flawList = ref([]);
const total = ref(0);
const imageViewerVisible = ref(false);
const currentImages = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

// 计算属性
const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const modalTitle = computed(() => `${props.flawType} - 缺陷详情`);

// 获取严重程度标签类型
const getSeverityTagType = (severity) => {
  const typeMap = {
    '轻微': 'info',
    '一般': 'warning', 
    '严重': 'danger',
    '紧急': 'danger'
  };
  return typeMap[severity] || 'info';
};

// 根据confirmed和uploaded字段计算缺陷处理状态
const getFlawStatus = (flaw) => {
  if (!flaw.confirmed) {
    return '待确认';
  } else if (flaw.confirmed && !flaw.uploaded) {
    return '待处理';
  } else if (flaw.confirmed && flaw.uploaded) {
    return '已处理';
  }
  return '未知';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    '待确认': 'warning',
    '待处理': 'danger',
    '已处理': 'success',
    '未知': 'info'
  };
  return typeMap[status] || 'info';
};

// 查看图片
const handleViewImage = (row) => {
  // 使用实际的图片URL，如果没有则使用占位图
  const images = [];
  if (row.flawImageUrl) {
    images.push(row.flawImageUrl);
  } else {
    // 使用占位图
    images.push(`https://picsum.photos/800/600?random=${row.id}`);
  }
  
  currentImages.value = images;
  imageViewerVisible.value = true;
};

// 获取缺陷列表
const getFlawList = async () => {
  if (!props.flawType) return;
  
  loading.value = true;
  try {
    const response = await getFlawsByTime(props.startTime, props.endTime);
    
    if (response.data.code === '200' || response.data.code === 200) {
      const allFlaws = response.data.rows
      
      // 根据缺陷类型筛选
      const filteredFlaws = allFlaws.filter(flaw => flaw.flawType === props.flawType);
      
      // 前端分页
      const start = (queryParams.pageNum - 1) * queryParams.pageSize;
      const end = start + queryParams.pageSize;
      
      flawList.value = filteredFlaws.slice(start, end);
      total.value = filteredFlaws.length;
    } else {
      throw new Error(response.msg || '获取数据失败');
    }
    
  } catch (error) {
    console.error('获取缺陷列表失败:', error);
    flawList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    queryParams.pageNum = 1;
    getFlawList();
  }
});

// 监听缺陷类型变化
watch(() => props.flawType, () => {
  if (props.visible) {
    queryParams.pageNum = 1;
    getFlawList();
  }
});
</script>

<style lang="scss" scoped>
@use '../../assets/scss/variables' as *;

.flaw-type-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .time-range,
    .flaw-type {
      font-size: 14px;
      color: $text-color-regular;
    }
  }
  
  .pagination {
    margin-top: 20px;
    justify-content: center;
  }
}
</style> 